package com.example.lib;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class ServerSocketThread {
    private BufferedReader in;
    private PrintWriter pw;
    private Socket socket;

    private int id;
    public ServerSocketThread(Socket socket, int id){
        this.socket = socket;
        this.id = id;
    }


    public void onStart(){
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                    pw = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true);

                    String content;
                    if (MyClass.player_num!=2) return;
                    content = in.readLine();

                    System.out.println(content);
                    //4.和客户端通信
                    if (content.equals("Coming")) {
                        pw.println("you are in game!");
                    } else if (content.equals("DIE")) {
                        System.out.println(content);
                        if (id == 1) MyClass.player1_alive = false;
                        else MyClass.player2_alive = false;
                    } else {
                        if (id == 1) MyClass.player1_score = Integer.parseInt(content);
                        else MyClass.player2_score = Integer.parseInt(content);

                    }
                    if (id == 1){
                        if (!MyClass.player2_alive) pw.println("XCH ALIVE");
                        pw.println(MyClass.player2_score);
                    }
                    else {
                        if (!MyClass.player1_alive) pw.println("XCH ALIVE");
                        pw.println(MyClass.player1_score);
                    }


                } catch (IOException e) {

                    throw new RuntimeException(e);
                }
            }
        };

        Timer timer = new Timer();
        // 定义开始等待时间  --- 等待 5 秒
        // 1000ms = 1s
        long delay = 0;
        // 定义每次执行的间隔时间
        long intevalPeriod = 100;
        // schedules the task to be run in an interval
        // 安排任务在一段时间内运行
        timer.scheduleAtFixedRate(task, delay, intevalPeriod);

    }
}
